#include "uart.c"
#include <regx52.h>

sbit BTN_TR0 = P2 ^ 0;
sbit BTN_ET0 = P2 ^ 1;
sbit BTN_EA = P2 ^ 2;
sbit BTN_THTL = P2 ^ 3;

void timer0_init()
{
    // timer0 模式1: 使用TH0+TL0 计数
    TMOD &= 0xF0;
    TMOD |= 0x01;

    // 11.0592MHZ 对应1ms的计数
    // TH0 = 0xFC;
    // TL0 = 0x66;

    TH0 = 0xDB;
    TL0 = 0xFF;

    // 启动Timer0，启动之后TH0+TL0计数
    TR0 = 1;
    // timer0的中断使能
    ET0 = 1;
    // 中断总开关
    EA = 1;
    // 调整中断优先级，需要在timer0中断调用串口打印设置优先级
    PT0 = 1;
}

unsigned int counter = 0;

/**
 * ISR​​ 是 ​​Interrupt Service Routine​​
 * 即​​中断服务程序​​ 或 ​中断服务例程​​。
 *
 * 12MHZ   (1/12) * 12 = 1us
 * 1us * 1000 = 1ms
 *
 * 65536 - 1000 = 64536 => FC18
 *
 * 100ms
 * 65536 - 100000 = 55536 => D8F0
 *
 * 11.0592MHZ
 * 1/11059200 * 12 = 1.085us
 * 1000 / 1.085 = 922
 * 65536 - 922 = 64614 => FC66
 *
 * 10ms
 * 10000 / 1.085 = 9217
 * 65536 - 9217 = 56319
 */
void timer0_ISR() interrupt 1
{
    // 进入中断重新装填初始值，确保下一次时间还是1ms
    // 不装填则从00开始计数
    // TH0 = 0xFC;
    // TL0 = 0x66;
    TH0 = 0xDB;
    TL0 = 0xFF;

    if (counter >= 100)
    {
        printf("timer0 interrupt!\n");
        counter = 0;
    }
    else
    {
        counter++;
    }
}

/**
 * TH0 + TL0 拼接成一个int返回
 * 0xAB + 0xCD  = 0xABCD
 *
 * 0x00  0xFF  + 1 = 0x01 0x00
 */
unsigned int get_timer0_value()
{
    unsigned char high, low;

    do
    {
        high = TH0;
        low = TL0;
    } while (high != TH0);

    // (high << 8) 表达式数据类型是int
    return (high << 8) | low;
}

void main()
{

    uart_init();
    timer0_init();
    while (1)
    {
        if (BTN_TR0 == 0)
        {
            while (BTN_TR0 == 0)
            {
            }
            TR0 = ~TR0;
            printf("TR0=%d\n", (int)TR0);
        }
        if (BTN_ET0 == 0)
        {
            while (BTN_ET0 == 0)
            {
            }
            ET0 = ~ET0;
            printf("ET0=%d\n", (int)ET0);
        }

        if (BTN_EA == 0)
        {
            while (BTN_EA == 0)
            {
            }
            EA = ~EA;
            printf("EA=%d\n", (int)EA);
        }
        if (BTN_THTL == 0)
        {
            while (BTN_THTL == 0)
            {
            }
            printf("TH0TL0=0x%04x\n", get_timer0_value());
        }
    }
}
